#ifndef WIN_UDP_SOCKET_HPP
#define WIN_UDP_SOCKET_HPP
#include "env.h"
#include <cstdio>

#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

// 封装一下socket
class winUDPSocket {
  public:
    winUDPSocket();
    ~winUDPSocket();
    int Send(const char *buffer, int length);
    int Resv(char *buffer, int length);
    // int Bind();
    int Close();
  private:
    SOCKET sock;
    sockaddr_in clientAddr;
    sockaddr_in dstAddr;
    sockaddr_in resvAddr;
    int addrLen = sizeof(resvAddr);
};

winUDPSocket::winUDPSocket() {
  WSADATA wsaData;
  WSAStartup(MAKEWORD(2, 2), &wsaData);
  sock = socket(PF_INET, SOCK_DGRAM, 0); // udp sock
  
  memset(&dstAddr, 0, sizeof(dstAddr));  //每个字节都用0填充
  dstAddr.sin_family = PF_INET; // IPv4 地址
  dstAddr.sin_addr.s_addr = inet_addr(SERVER_IP); // IPv4 地址
  dstAddr.sin_port = htons(SERVER_PORT); // 端口
}
winUDPSocket::~winUDPSocket() {
  Close();
}
int winUDPSocket::Close() {
  closesocket(sock);
  WSACleanup();
  system("pause");
  return 1;
}
int winUDPSocket::Send(const char *buffer, int length) {
  sendto(sock, buffer, length, 0, (struct sockaddr*)&dstAddr, sizeof(dstAddr));
  return 1;
}
int winUDPSocket::Resv(char *buffer, int length) {
  int strLen = recvfrom(sock, buffer, length, 0, (struct sockaddr*)&resvAddr, &addrLen);
  buffer[strLen] = 0;
  // printf("iP: %s\n", inet_ntoa(resvAddr.sin_addr));
  // printf("Message form server: %s\n", buffer);
  return 1;
}
// int winUDPSocket::Bind() {
//   sockaddr_in clientAddr;
//   memset(&clientAddr, 0, sizeof(clientAddr));  //每个字节都用0填充
//   clientAddr.sin_family = PF_INET;  //使用IPv4地址
//   clientAddr.sin_addr.s_addr = htonl(INADDR_ANY); //自动获取IP地址
//   clientAddr.sin_port = htons(1234);  //端口
//   bind(sock, (SOCKADDR*)&clientAddr, sizeof(SOCKADDR));
// }
#endif // WIN_UDP_SOCKET_HPP